package com.organization

class DepartmentService {

    def commonService

    def getDepartmentInfo(depId){
        Department dep = Department.get(commonService.nodeIdToDbId(depId))
        if (dep){
            def result = [name:dep.name, dateCreated:dep.dateCreated, description:dep.description]
            result.putAll(commonService.goodResponse)
            return result
        }
        return commonService.badResponse
    }

    def updateDepartmentInfo(params){
        Department dep = Department.get(commonService.nodeIdToDbId(params.nodeId))
        if (dep){
            dep.name = params.name
            dep.dateCreated = commonService.convertDateFromJson(params.dateCreated)
            dep.description = params.description
            if (dep.validate()){
                dep.save()
                def response = [:]
                response.putAll(commonService.goodResponse)
                response.putAt('newName',params.name)
                response.putAt('nodeId',params.nodeId)
                return response
            }
            else{
                return commonService.parseErrorsFromDomain(dep.errors)
            }
        }
        return commonService.badResponse
    }

    def addDepartment(params){
        Department dep = new Department(
                name: params.name,
                description: params.description
        );
        if (dep.save()){
            dep.dateCreated = commonService.convertDateFromJson(params.dateCreated)
            def response = [:]
            response.putAll(commonService.goodResponse)
            response.putAt('nodeId',commonService.depNodeStr+dep.id.toString())
            response.putAt('parentNodeId',params.parentNodeId)
            return response
        }
        else{
            return commonService.parseErrorsFromDomain(dep.errors)
        }
        return commonService.badResponse
    }

    def deleteDepartment(params){
        Department dep = Department.get(commonService.nodeIdToDbId(params.nodeId))
        if (dep){
            dep.delete()
            return commonService.goodResponse
        }
        return commonService.badResponse;
    }

}
